package com.gdkm.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gdkm.dao.UserDao;
import com.gdkm.daomain.User;

public class LoginServlet extends HttpServlet {
	private static final long seriaVersionUID=1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf8");
		request.setCharacterEncoding("utf8");
		UserDao userDao = new UserDao();
		HttpSession session = request.getSession();
		String op = request.getParameter("op");
		if (op != null && op.equals("login")) {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String checkcode = request.getParameter("checkcode");//填写验证码
			String randCode = (String) session.getAttribute("randCode");//生成验证码
			if (checkcode == null || !checkcode.equalsIgnoreCase(randCode)) {
				request.setAttribute("msg", "验证码错误");
				request.getRequestDispatcher("/manager/login.jsp").forward(request, response);
				return;
			}
			if (username != null && !username.trim().equals("") && password != null && !password.trim().equals("")) {
				try {
					User user = userDao.findUserByUsernameAndPassword(username, password);
					if (user != null) {// 登录成功
						session.setAttribute("user", user);
						String role = user.getRole();
						if (role.equals("博客管理员")) {// 管理员
							response.sendRedirect(request.getContextPath() + "/manager/main.jsp");
						} else {// 普通用户
							response.sendRedirect(request.getContextPath() + "/client/index.jsp");
						}
					} else {// 登录失败
						request.setAttribute("msg", "账号密码错误");
						request.getRequestDispatcher("/manager/login.jsp").forward(request, response);
					}
				} catch (SQLException e) {
					e.printStackTrace();
					request.setAttribute("msg", "登录失败");
					request.getRequestDispatcher("/manager/login.jsp").forward(request, response);
				}

			} else {// 账号密码为空
				request.setAttribute("msg", "账号密码不能为空");
				request.getRequestDispatcher("/manager/login.jsp").forward(request, response);
			}
			
		}
		//推出
		else if(op!=null && op.equals("logout")){
			session.invalidate();
			response.sendRedirect(request.getContextPath()+"/manager/login.jsp");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
